package 数组;

/**
 * @author TTDB
 * @create 2025/9/14
 */
public class rotate {
     public void rotate(int[] nums, int k) {
      //1,2,3,4,5,6,7   k = 3   5,6,7,1,2,3,4
         int n = nums.length;
         //法1：做一个新的数组
         int[] newNums = new int[n];
         for (int i = 0; i < n; i++) {
             newNums[(i + k) % n] = nums[i];
         }
         for(int i = 0; i < n; i++){
             nums[i] = newNums[i];
         }
    }

    public void rotate2(int[] nums, int k) {
        //1,2,3,4,5,6,7   k = 3   5,6,7,1,2,3,4
        //7,6,5,4,3,2,1
        //5,6,7,4,3,2,1
        //5,6,7,1,2,3,4
        int n = nums.length;
        k %= n; // 轮转 k 次等于轮转 k % n 次
        reverse(nums, 0, n - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, n - 1);
    }

    private void reverse(int[] nums, int i, int j) {
        while (i < j) {
            int temp = nums[i];
            nums[i++] = nums[j];
            nums[j--] = temp;
        }
    }
}
